package com.example.spel;

import jakarta.annotation.PostConstruct;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

import java.io.IOException;

@Configuration
@PropertySource("classpath:book.properties")
@EnableConfigurationProperties({Sample.class})
public class SPELConfig {

//    普通文本
    @Value("base text")
    private String text;

//    系统环境
    @Value("#{systemProperties['os.name']}")
    private String osName;


//    表达式计算
    @Value("#{T(java.lang.Math).random() * 100.0}")
    private double randomNumber;

//    @Value("#{com.example.spel.Sample.name}")
//    private String sampleName;

//    文件、网页、资源注入
    @Value("classpath:test.txt")
    private Resource testTxt;

    @Value("http://www.baidu.com")
    private Resource baidu;

    @Autowired
    private Environment environment;

    @Autowired
    private Sample sample;
    @PostConstruct
    public void init() {
        System.out.println(text);

        try {
            String contents = IOUtils.toString(testTxt.getInputStream(), "UTF-8");
            System.out.println(contents);
            System.out.println(IOUtils.toString(baidu.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Bean
    public static  PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}
